package pdm.yamba;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import pdm.yamba.dataAccess.DBProvider;
import pdm.yamba.dto.Status;
import pdm.yamba.feed.TwitterFeed;
import pdm.yamba.listener.IStatusRefreshListener;
import pdm.yamba.service.TimelinePullService;
import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

public class MainApplication extends Application 
{
	private SharedPreferences preferences;
	private TwitterFeed twitterFeed;
	private List<Status> statuses = new ArrayList<Status>();
	private SharedPreferences.OnSharedPreferenceChangeListener preferenceListener;
	List<IStatusRefreshListener> sListeners = new ArrayList<IStatusRefreshListener>();
	private DBProvider dbProvider;

	@Override
	public void onCreate() 
	{
		super.onCreate();
		
		// load the preferences
		preferenceListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
		    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) 
		    {
		        if (key.equals("timelineLength") && twitterFeed != null) 
		        {
		        	RefreshStatusViaService();
		        }
		        else 
		        {
		        	if(canLogInFeed() && (key.equals("serviceUri") || key.equals("username") || key.equals("password")))
		        	{
		        		createTwitterFeed();
		        	}
		        }
		    }
		};
		
		preferences = PreferenceManager.getDefaultSharedPreferences(this);
		preferences.registerOnSharedPreferenceChangeListener(preferenceListener);
		
		// check if the required Preferences are specified
		if(!isMinPreferencesSpecified())
		{
			Log.v("APP", "Redirecting...");
			Intent intent = new Intent(this, PreferencesActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
			Log.v("APP", "Redirected...");
		}
		
		if(canLogInFeed()) 
		{
			createTwitterFeed();
		}
		
		boolean flag = isOnline();
		
	    try {
	    	
	    	
	        String destPath = "/data/data/pdm.yamba/databases/YambaDB";
	        File f = new File(destPath);
	        if (!f.exists()) {
	          CopyDB(getBaseContext().getAssets().open("YambaDB"),
	              new FileOutputStream(destPath));
	        }
	      } catch (FileNotFoundException e) {
	        e.printStackTrace();
	      } catch (IOException e) {
	        e.printStackTrace();
	      }		
	    dbProvider = new DBProvider(this);	    
	}
	
	  private void CopyDB(InputStream inputStream, OutputStream outputStream)
		      throws IOException {
		    byte[] buffer = new byte[1024];
		    int length;
		    while ((length = inputStream.read(buffer)) > 0) {
		      outputStream.write(buffer, 0, length);
		    }
		    inputStream.close();
		    outputStream.close();
		  }	
	
	  public boolean isOnline() {
		    ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		    NetworkInfo netInfo = cm.getActiveNetworkInfo();
		    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
		        return true;
		    }
		    return false;
		}	  
	  
		public DBProvider getDBProvider()
		{
			return dbProvider;
		}	  
	  
	@Override
	public void onTerminate() 
	{
		super.onTerminate();
		// clear all preferences and memory
		clear();
	}
	
	private void createTwitterFeed()
	{
		twitterFeed = new TwitterFeed(getUsername(), getPassword(), getServiceUri());
		
		// listen for changes whenever a refresh occurs, to update the statuses stored in memory
		/*twitterFeed.addStatusRefreshListener(new IStatusRefreshListener() 
		{
			@Override
			public void onRefreshComplete(List<Status> newStatuses) 
			{
				//int twitterStatusLength = getTimelineLength(); // > newStatuses.size() ? newStatuses.size() : getTimelineLength();
				//for(int i= 0; i < twitterStatusLength; ++i)
		    	//{
		    	//	Status tStatus = newStatuses.get(i);
		    	//	statuses.add(tStatus);
		    	//}
			}

			@Override
			public void onRefreshProgress(Status status) 
			{
				if(statuses.size() < getTimelineLength()) 
				{
					statuses.add(status);
			    	for (IStatusRefreshListener hl : sListeners) 
			    		hl.onRefreshProgress(status);
				}
			}
        });	
		*/
		// get the lastest statuses
		//twitterFeed.Refresh(getTimelineLength());

		
		
		Intent myIntent = new Intent(MainApplication.this, TimelinePullService.class);
		PendingIntent pendingIntent = PendingIntent.getService(MainApplication.this, 0, myIntent, 0);
		AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
		Calendar calendar = Calendar.getInstance();
		alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 15*1000, pendingIntent);
	
	}
	
	public TwitterFeed getTwitterFeed()
	{
		return twitterFeed;
	}
	
	public void PublishStatus(Status status)
	{
		twitterFeed.Publish(status);
	}
	
	public void PublishStatusViaService(String message)
	{
		twitterFeed.PublishViaService(message);
	}	

	public void RefreshStatus()
	{
		statuses.clear();
		twitterFeed.Refresh(getTimelineLength());
	}	
	
	public void RefreshStatusViaService()
	{
		statuses.clear();
		statuses = twitterFeed.RefreshViaService(getTimelineLength());
	}
	
	
	public List<Status> getStatuses() 
	{
		return statuses;
	}
	
	public String getUsername() 
	{
		return preferences.getString("username", "");
	}
	
	public String getPassword()
	{
		return preferences.getString("password", "");		
	}
	
	public String getServiceUri()
	{
		return preferences.getString("serviceUri", "");		
	}
	
	public int getStatusLength()
	{
		return Integer.valueOf(preferences.getString("statusLength", "140"));		
	}
	
	public int getTimelineLength()
	{
		return Integer.valueOf(preferences.getString("timelineLength", "70"));		
	}
	
	public boolean getAutomaticTimelineUpdate()
	{
		return Boolean.valueOf(preferences.getString("automaticTimelineUpdate", "false"));		
	}
	
	
	
	public boolean isMinPreferencesSpecified()
	{
		return getUsername() != "" && getServiceUri() != "";
	}
	
	public boolean canLogInFeed() 
	{
		return isMinPreferencesSpecified() && getPassword() != "";
	}
	
	public void addStatusRefreshListener(IStatusRefreshListener eventListener) 
	{
		sListeners.add(eventListener);
	}
	
	private void clear() 
	{
		// clear
		Editor editor = preferences.edit();
		editor.clear();
		editor.commit();		
	}
}
